<?php
namespace app\home\controller;

use app\common\component\user\UserModel;
use app\common\component\user\UserService;
use app\common\component\user\UserValidate;
use app\common\component\user_activation_log\UserActivationLogService;

class Auth extends ControllerBase {
	public function login() {
		$post = $this -> request -> post();

		$resultUserValidate = (new UserValidate) -> login($post);
		if($resultUserValidate['code'] !== 0) {
			return json($resultUserValidate);
		}

		$loginUser = (new UserService) -> login($post);
		return json($loginUser);
	}

	public function forgetPassword() {
		$post = $this -> request -> post();

		$getUser = UserModel::get(['username' => $post['username']]);

		if(!$getUser) {
			return [
				'code' => -1,
				'message' => '账号不存在！'
			];
		}

		$code = \think\Cache::get('sendCode_'.$getUser -> user_id);

		if(!$code) {
			return [
				'code' => -1,
				'message' => '验证码错误！'
			];
		}
	
		if($code != $post['code']) {
			return [
				'code' => -1,
				'message' => '验证码错误！'
			];
		}
		
		if($post['password'] != $post['comfirm_password']) {
			return [
				'code' => -1,
				'message' => '输入的密码不一致！'
			];
		}

		$getUser -> password = getPasswordHash($post['password']);
		
		if($getUser -> save()) {
			return [
				'code' => 0,
				'message' => '修改成功！'
			];
		}

		return [
			'code' => -1,
			'message' => '修改失败！'
		];
	}

	public function sendCode() {
		$result = ['code' => -1, 'message' => '非法操作!'];
		$post = $this -> request -> post();
		$getUser = UserModel::get(['username' => $post['username']]);

		if(!$getUser) {
			$result['code'] = -1;
			$result['message'] = '账号不存在';
		} else {
			$code = rand(22222, 99999);
			\think\Cache::set('sendCode_'.$getUser -> user_id, $code, 300);

			$result['code'] = 0;
			$result['message'] = winicSMS($getUser -> phone, ['code' => $code], 90);
		}

		return json($result);
	}

	public function logout() {
		(new UserService) -> clearLoginSession();
		$this -> redirect('home/Index/index');
	}

	public function register() {
		$post = $this -> request -> post();
		$post['createtime'] = time();
		$post['status'] = 1;

		$resultUserValidate = (new UserValidate) -> create($post);
		if($resultUserValidate['code'] !== 0) {
			return json($resultUserValidate);
		}
		/*
		$getPromotionUser = UserModel::get(['username' => $post['promotion_username']]);
		$resultGetUserActivation = (new \app\common\component\user_activation\UserActivationService) -> getUserActivationId($getPromotionUser['user_id']);
		if($resultGetUserActivation['data']['user_activation'] -> price <= 0) {
			return json(['code' => -1, 'message' => '推广人账号激活码不足!']);
		}
		*/
		\think\Db::startTrans();
		try {
			/*
			$resultUserActivationLogServiceLog = (new UserActivationLogService()) -> log(2, 0, 1, $post['promotion_username'], $post['username'], '激活码使用', 1);
			if($resultUserActivationLogServiceLog['code'] !== 0) {
				throw new \Exception($resultUserActivationLogServiceLog['message']);
			}

			if(!$resultGetUserActivation['data']['user_activation'] -> setDec('price', 1)) {
				throw new \Exception('注册失败!');
			}
			*/
			$resultCreateUser = (new UserService) -> create($post);
			if($resultCreateUser['code'] !== 0) {
				throw new \Exception('注册失败!');
			}

			// 注册商城用户
			$shopUsers = new \app\common\model\ShopUsers([
				'mobile' => $resultCreateUser['data']['user'] -> phone,
				'password' => md5('TPSHOP'.$post['password']),
				'nickname' => $post['username'],
				'sex' => 0,
				'reg_time' => $post['createtime'],
			]);
			if(!$shopUsers -> save()) {
				throw new \Exception('注册失败!');
			}

			\think\Db::commit();
		} catch(\Exception $e) {
			\think\Db::rollback();

			return json(['code' => 0, 'message' => $e -> getMessage()]);
		}

		return json(['code' => 0, 'message' => '注册成功']);
	}

	public function handleStatus() {
		$userId = \think\Session::get('user_id');

		$getUserActivation = (new \app\common\component\user_activation\UserActivationService) -> getUserActivationId($userId);
		if($getUserActivation['data']['user_activation'] -> price <= 0) {
			echo '<meta charset="utf-8"><script>alert("激活码不足!");window.location.href="/promotion/down";</script>';exit;
		}

		$get = $this -> request -> get();

		$getDownUser = UserModel::get(['user_id' => $get['user_id']]);
		if(!$getDownUser || $getDownUser -> getData('status') == 0) {
			echo '<meta charset="utf-8"><script>alert("激活的用户不存在或已经激活!");window.location.href="/promotion/down";</script>';exit;
		}

		\think\Db::startTrans();
		try {
			$resultUserActivationLogServiceLog = (new UserActivationLogService()) -> log(2, 0, 1, \think\Session::get('user_name'), $getDownUser['username'], '激活码使用', 1);
			if($resultUserActivationLogServiceLog['code'] !== 0) {
				throw new \Exception($resultUserActivationLogServiceLog['message']);
			}

			if(!$getUserActivation['data']['user_activation'] -> setDec('price', 1)) {
				throw new \Exception('激活失败!');
			}

			$getDownUser -> status = 0;
			if(!$getDownUser -> save()) {
				throw new \Exception('激活失败!');
			}

			\think\Db::commit();
		} catch(\Exception $e) {
			\think\Db::rollback();

			echo '<meta charset="utf-8"><script>alert("' . $e -> getMessage() . '");window.location.href="/promotion/down";</script>';exit;
		}

		echo '<meta charset="utf-8"><script>alert("激活成功");window.location.href="/promotion/down";</script>';exit;
	}
}